package com.wxzz.elearing.evaluation.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.evaluation.amqp.EvaluationProducer;
import com.wxzz.elearing.evaluation.dto.*;
import com.wxzz.elearing.evaluation.entity.*;
import com.wxzz.elearing.evaluation.mapper.*;
import com.wxzz.elearing.evaluation.service.IBusinessCategoryRuleService;
import com.wxzz.elearing.evaluation.service.openfeign.IEnterpriseApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IEnterpriseOrganizationApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.evaluation.vo.CredentialListVo;
import com.wxzz.elearing.evaluation.vo.CredentialVo;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.dto.FeignEnterpriseDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.ExcelUtils;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 工厂体检/星级认证 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-10
 */
@Service
public class BusinessCategoryRuleServiceImpl extends ServiceImpl<BusinessCategoryRuleMapper, BusinessCategoryRule> implements IBusinessCategoryRuleService {

    @Autowired
    private BusinessCategoryRuleMapper businessCategoryRuleMapper;

    @Autowired
    private BusinessCategoryMapper businessCategoryMapper;

    @Idempotent
    @Override
    public ReturnVO saveBusinessCategoryRule(BusinessCategoryRule businessCategoryRule) {
        //工厂体检
        businessCategoryRule.setType(0);
        if (businessCategoryRule.getId() == null) {
            BusinessCategoryRule temp = businessCategoryRuleMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRule>()
                    .eq(BusinessCategoryRule::getBusinessCategoryId, businessCategoryRule.getBusinessCategoryId())
                    .eq(BusinessCategoryRule::getType, 0));
            if (temp != null) {
                throw new ServiceException("该行业已存在");
            }
            businessCategoryRuleMapper.insert(businessCategoryRule);
        } else {
            BusinessCategoryRule temp = businessCategoryRuleMapper.selectById(businessCategoryRule.getId());
            if (temp.getBusinessCategoryId() != null && !temp.getBusinessCategoryId().equals(businessCategoryRule.getBusinessCategoryId())) {
                BusinessCategoryRule selectOne = businessCategoryRuleMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRule>()
                        .eq(BusinessCategoryRule::getBusinessCategoryId, businessCategoryRule.getBusinessCategoryId())
                        .eq(BusinessCategoryRule::getType, 0));

                if (selectOne != null) {
                    throw new ServiceException("该行业已存在");
                }
            }
            businessCategoryRuleMapper.updateById(businessCategoryRule);
        }
        return new ReturnVO("工厂体检新增成功", businessCategoryRule.getId());
    }


    @Override
    public ReturnVO deleteBusinessCategoryRuleById(Long businessCategoryRuleId) {
        businessCategoryRuleMapper.deleteById(businessCategoryRuleId);
        return new ReturnVO("删除成功", businessCategoryRuleId);
    }

    @Override
    public ReturnVO saveBusinessCategoryRule4start(BusinessCategoryRule businessCategoryRule) {
        //星级认证
        businessCategoryRule.setType(1);
        if (businessCategoryRule.getId() == null) {
            businessCategoryRuleMapper.insert(businessCategoryRule);
        } else {
            businessCategoryRuleMapper.updateById(businessCategoryRule);
        }
        return new ReturnVO("星级认证新增成功", businessCategoryRule.getId());
    }

    @Override
    public Integer selectTopStarByWxUserId(Long wxUserId) {
        BusinessCategoryRuleHistory businessCategoryRuleHistory = businessCategoryRuleHistoryMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getWxUserId, wxUserId)
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .last("limit 0,1"));
        if (businessCategoryRuleHistory != null && businessCategoryRuleHistory.getStartLevel() != null) {
            return businessCategoryRuleHistory.getStartLevel();
        }
        return 0;
    }

    @Autowired
    private BusinessCategoryTopicMapper businessCategoryTopicMapper;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryRule>>> listBusinessCategoryRule(Integer type, BusinessCategoryRuleDto businessCategoryRuleDto) {
        PageHelper.startPage(businessCategoryRuleDto.getCurPage(), businessCategoryRuleDto.getMaxPage());
        QueryWrapper<BusinessCategoryRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("type", type);
        if (businessCategoryRuleDto.getBusinessCategoryId() != null) {
            queryWrapper.eq("business_category_id", businessCategoryRuleDto.getBusinessCategoryId());
        }
        if (StringUtils.isNotBlank(businessCategoryRuleDto.getRuleName())) {
            queryWrapper.like("rule_name", businessCategoryRuleDto.getRuleName());
        }
        List<BusinessCategoryRule> businessCategoryRules = businessCategoryRuleMapper.selectList(queryWrapper);
        businessCategoryRules.forEach(businessCategoryRule -> {
            BusinessCategory businessCategory = businessCategoryMapper.selectById(businessCategoryRule.getBusinessCategoryId());
            if (businessCategory != null) {
                businessCategoryRule.setBusinessName(businessCategory.getBusinessName());
            }
            //题目数量
            Integer topicNum = businessCategoryTopicMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryTopic>()
                    .eq(BusinessCategoryTopic::getCommonId, businessCategoryRule.getId()));
            businessCategoryRule.setTopicNum(topicNum);
            //测评人数
            Integer testNum = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                    .eq(BusinessCategoryRuleHistory::getBusinessCategoryRuleId, businessCategoryRule.getId()));
            businessCategoryRule.setTestNum(testNum);
        });
        return new ReturnVO("工厂体检/星级认证列表查询成功", new JgPageVo<>(new PageInfo(businessCategoryRules)));
    }

    @Autowired
    private TopicMapper topicMapper;

    @Transactional
    @Override
    public ReturnVO saveBusinessCategoryTopic(Integer type, BusinessCategoryTopicInsDto businessCategoryTopicInsDto) {
        if (businessCategoryTopicInsDto.getTopicIds() != null) {
            for (Long topicId : businessCategoryTopicInsDto.getTopicIds()) {
                Integer count = businessCategoryTopicMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryTopic>()
                        .eq(BusinessCategoryTopic::getTopicId, topicId)
                        .eq(BusinessCategoryTopic::getType, type)
                        .eq(BusinessCategoryTopic::getCommonId, businessCategoryTopicInsDto.getCommonId()));
                if (count > 0) {
                    Topic topic = topicMapper.selectById(topicId);
                    if (topic != null) {
                        throw new ServiceException("题目[" + topic.getTopicName() + "]已经存在该项目");
                    }
                }
                BusinessCategoryTopic businessCategoryTopic = new BusinessCategoryTopic();
                businessCategoryTopic.setBusinessCategoryId(businessCategoryTopicInsDto.getBusinessCategoryId());
                businessCategoryTopic.setTopicId(topicId);
                businessCategoryTopic.setType(type);
                businessCategoryTopic.setCommonId(businessCategoryTopicInsDto.getCommonId());
                businessCategoryTopicMapper.insert(businessCategoryTopic);
            }
        }
        return new ReturnVO("题库添加成功", businessCategoryTopicInsDto.getCommonId());
    }

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryRule>>> listBusinessCategoryRuleByCategory(Long wxUserId, WxBusinessCategoryRuleDto wxBusinessCategoryRuleDto) {
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(wxUserId);
        List<BusinessCategoryRule> businessCategoryRules = null;
        if ("200".equals(stringReturnVO.getCode())) {
            JSONObject jsonObject = JSONObject.parseObject(stringReturnVO.getData());
            //取出企业的行业类目id
            Long businessCategoryId = jsonObject.getLong("businessCategoryId");
            PageHelper.startPage(wxBusinessCategoryRuleDto.getCurPage(), wxBusinessCategoryRuleDto.getMaxPage());
            QueryWrapper<BusinessCategoryRule> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("business_category_id", businessCategoryId);
            if (StringUtils.isNotBlank(wxBusinessCategoryRuleDto.getRuleName())) {
                queryWrapper.like("rule_name", wxBusinessCategoryRuleDto.getRuleName() + "%");
            }
            businessCategoryRules = businessCategoryRuleMapper.selectList(queryWrapper);
            //需要移除的对象
            List<BusinessCategoryRule> needRemove = Lists.newArrayList();
            //筛选用户绑定
            for (BusinessCategoryRule businessCategoryRule : businessCategoryRules) {
                List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroup = businessCategoryRuleMapper.selectBusinessCategoryRule4startId(wxUserId, businessCategoryRule.getId());
                if (wxUserBusinessCategoryGroup.size() == 0) {
                    needRemove.add(businessCategoryRule);
                }

                //查出该企业的所有班组
                List<BusinessCategoryRuleGroup> businessCategoryRuleGroupList = businessCategoryRuleGroupMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleGroup>()
                        .eq(BusinessCategoryRuleGroup::getBusinessCategoryRuleId, businessCategoryRule.getId())
                        .eq(BusinessCategoryRuleGroup::getEnterpriseId, jsonObject.getLong("id")));
                //计算测评人数
                Integer testNum = 0;
                for (BusinessCategoryRuleGroup businessCategoryRuleGroup : businessCategoryRuleGroupList) {
                    Integer count = wxUserBusinessCategoryGroupMapper.selectCount(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                            .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryRuleGroup.getId())
                            .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                            .eq(WxUserBusinessCategoryGroup::getEnterpriseId, jsonObject.getLong("id"))
                            .eq(WxUserBusinessCategoryGroup::getType, 0));
                    testNum = testNum + count;
                }
                businessCategoryRule.setTestNum(testNum);
            }
            businessCategoryRules.removeAll(needRemove);
        }
        return new ReturnVO("星级认证查询成功", new JgPageVo<>(new PageInfo(businessCategoryRules)));
    }

    @Autowired
    private BusinessCategoryRuleHistoryMapper businessCategoryRuleHistoryMapper;

    @Autowired
    private IEnterpriseOrganizationApiFeign enterpriseOrganizationApiFeign;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryRuleHistory>>> listBusinessCategoryRuleHistory(BusinessCategoryRuleHistoryDto businessCategoryRuleHistoryDto) {
        PageHelper.startPage(businessCategoryRuleHistoryDto.getCurPage(), businessCategoryRuleHistoryDto.getMaxPage());
        QueryWrapper<BusinessCategoryRuleHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        if (businessCategoryRuleHistoryDto.getStartTimeStart() != null && businessCategoryRuleHistoryDto.getStartTimeEnd() != null) {
            queryWrapper.between("create_time", businessCategoryRuleHistoryDto.getStartTimeStart().toString(), businessCategoryRuleHistoryDto.getStartTimeEnd().toLocalDate().toString() + " 23:59");
        }
        if (StringUtils.isNotBlank(businessCategoryRuleHistoryDto.getRuleName())) {
            queryWrapper.like("rule_name", businessCategoryRuleHistoryDto.getRuleName() + "%");
        }
        if (businessCategoryRuleHistoryDto.getBusinessCategoryId() != null) {
            queryWrapper.eq("business_category_id", businessCategoryRuleHistoryDto.getBusinessCategoryId());
        }
        if (businessCategoryRuleHistoryDto.getType() != null) {
            queryWrapper.eq("type", businessCategoryRuleHistoryDto.getType());
        }
        if (businessCategoryRuleHistoryDto.getWxUserId() != null) {
            queryWrapper.eq("wx_user_id", businessCategoryRuleHistoryDto.getWxUserId());
        }
        if (businessCategoryRuleHistoryDto.getBusinessCategoryRuleId() != null) {
            queryWrapper.eq("business_category_rule_id", businessCategoryRuleHistoryDto.getBusinessCategoryRuleId());
        }
        if (businessCategoryRuleHistoryDto.getEnterpriseId() != null) {
            queryWrapper.eq("enterprise_id", businessCategoryRuleHistoryDto.getEnterpriseId());
        }
        if (businessCategoryRuleHistoryDto.getEnterpriseOrganizationId() != null) {
            queryWrapper.eq("enterprise_organization_id", businessCategoryRuleHistoryDto.getEnterpriseOrganizationId());
        }
        if (businessCategoryRuleHistoryDto.getStartLevel() != null) {
            queryWrapper.eq("start_level", businessCategoryRuleHistoryDto.getStartLevel());
        }
        List<BusinessCategoryRuleHistory> businessCategoryRuleHistories = businessCategoryRuleHistoryMapper.selectList(queryWrapper);
        for (BusinessCategoryRuleHistory businessCategoryRuleHistory : businessCategoryRuleHistories) {
            if (businessCategoryRuleHistory.getEnterpriseOrganizationId() != null) {
                ReturnVO<String> stringReturnVO = enterpriseOrganizationApiFeign.selectOrganizationById(businessCategoryRuleHistory.getEnterpriseOrganizationId());
                JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
                businessCategoryRuleHistory.setOrganizationName(jsonObject.getString("organizationName"));
            }
        }
        return new ReturnVO("工厂体检/星级认证历史查询成功", new JgPageVo<>(new PageInfo(businessCategoryRuleHistories)));
    }

    @Override
    public ReturnVO selectBusinessCategoryRuleById(JSONObject jsonObject, Long businessCategoryRuleId) {
        BusinessCategoryRule businessCategoryRule = businessCategoryRuleMapper.selectById(businessCategoryRuleId);
        Optional.ofNullable(businessCategoryRule).orElseThrow(() -> new ServiceException("星级认证详情查询失败"));
        //题目数量
        Integer topicNum = businessCategoryTopicMapper.countTopicJoinBusinessCategoryTopic(1, businessCategoryRuleId);
        businessCategoryRule.setTopicNum(topicNum);
        //是否测评过
        Integer testHistoryNum = businessCategoryRuleHistoryMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getBusinessCategoryRuleId, businessCategoryRuleId)
                .eq(BusinessCategoryRuleHistory::getWxUserId, jsonObject.getLong("id")));
        if (testHistoryNum > 0) {
            businessCategoryRule.setIsTest(1);
        }
        //查出该企业的所有班组
        List<BusinessCategoryRuleGroup> businessCategoryRuleGroupList = businessCategoryRuleGroupMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleGroup>()
                .eq(BusinessCategoryRuleGroup::getBusinessCategoryRuleId, businessCategoryRuleId)
                .eq(BusinessCategoryRuleGroup::getEnterpriseId, jsonObject.getLong("enterpriseId")));
        //计算测评人数
        Integer testNum = 0;
        for (BusinessCategoryRuleGroup businessCategoryRuleGroup : businessCategoryRuleGroupList) {
            Integer count = wxUserBusinessCategoryGroupMapper.selectCount(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                    .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryRuleGroup.getId())
                    .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                    .eq(WxUserBusinessCategoryGroup::getEnterpriseId, jsonObject.getLong("id"))
                    .eq(WxUserBusinessCategoryGroup::getType, 0));
            testNum = testNum + count;
        }
        businessCategoryRule.setTestNum(testNum);
        return new ReturnVO("星级认证详情查询成功", businessCategoryRule);
    }

    @Autowired
    private BusinessCategoryRuleGroupMapper businessCategoryRuleGroupMapper;

    @Autowired
    private WxUserBusinessCategoryGroupMapper wxUserBusinessCategoryGroupMapper;

    @Idempotent
    @Transactional
    @Override
    public ReturnVO saveBusinessCategoryRuleGroup(Long enterpriseId, BusinessCategoryRuleGroupInsDto businessCategoryRuleGroupInsDto) {
        BusinessCategoryRule businessCategoryRule = businessCategoryRuleMapper.selectById(businessCategoryRuleGroupInsDto.getBusinessCategoryRuleId());
        Optional.ofNullable(businessCategoryRule).orElseThrow(() -> new ServiceException("该星级认证已不存在"));
        if (businessCategoryRuleGroupInsDto.getId() == null) {
            BusinessCategoryRuleGroup businessCategoryRuleGroup = new BusinessCategoryRuleGroup();
            businessCategoryRuleGroup.setRuleName(businessCategoryRule.getRuleName());
            businessCategoryRuleGroup.setBusinessCategoryRuleId(businessCategoryRuleGroupInsDto.getBusinessCategoryRuleId());
            businessCategoryRuleGroup.setEnterpriseId(enterpriseId);
            businessCategoryRuleGroup.setEnterpriseOrganizationId(businessCategoryRuleGroupInsDto.getEnterpriseOrganizationId());
            businessCategoryRuleGroupMapper.insert(businessCategoryRuleGroup);
            //添加绑定人员
            if (businessCategoryRuleGroupInsDto.getWxUserIds() != null) {
                for (Long wxUserId : businessCategoryRuleGroupInsDto.getWxUserIds()) {
                    //查询用户是否参与
                    List<WxUserBusinessCategoryGroup> result = businessCategoryRuleMapper.selectBusinessCategoryRule4startId(wxUserId, businessCategoryRule.getId());
                    if (result.size() > 0) {
                        FeignWxUserDto feignWxUserDto = wxUserApiFeign.selectFeignWxUserDtoByWxUserId(wxUserId);
                        throw new ServiceException("用户" + feignWxUserDto.getNickname() + "已经参与此星级认证");
                    }
                    WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = new WxUserBusinessCategoryGroup();
                    wxUserBusinessCategoryGroup.setCommonId(businessCategoryRuleGroup.getId());
                    wxUserBusinessCategoryGroup.setEnterpriseId(enterpriseId);
                    wxUserBusinessCategoryGroup.setType(0);
                    wxUserBusinessCategoryGroup.setWxUserId(wxUserId);
                    wxUserBusinessCategoryGroupMapper.insert(wxUserBusinessCategoryGroup);
                }
                //todo 小程序订阅
                SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                systemMessageMqDto.setMessageDetail("您已被纳入" + businessCategoryRule.getRuleName() + "星级认证中,请及时完成测评");
                systemMessageMqDto.setMessageTitle("星级认证");
                systemMessageMqDto.setWxUserIds(businessCategoryRuleGroupInsDto.getWxUserIds());
                evaluationProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
            }
        } else {
            BusinessCategoryRuleGroup businessCategoryRuleGroup = businessCategoryRuleGroupMapper.selectById(businessCategoryRuleGroupInsDto.getId());
            Optional.ofNullable(businessCategoryRuleGroup).orElseThrow(() -> new ServiceException("该id对应的星级认证班组不存在"));
            businessCategoryRuleGroup.setEnterpriseOrganizationId(businessCategoryRuleGroupInsDto.getEnterpriseOrganizationId());
            businessCategoryRuleGroup.setEnterpriseId(enterpriseId);
            businessCategoryRuleGroup.setBusinessCategoryRuleId(businessCategoryRuleGroupInsDto.getBusinessCategoryRuleId());
            businessCategoryRuleGroupMapper.updateById(businessCategoryRuleGroup);

            //先全部禁考
            List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroups = wxUserBusinessCategoryGroupMapper.selectList(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                    .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                    .eq(WxUserBusinessCategoryGroup::getType, 0)
                    .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryRuleGroup.getId()));
            for (WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup : wxUserBusinessCategoryGroups) {
                //禁考
                wxUserBusinessCategoryGroup.setExamStatus(1);
                wxUserBusinessCategoryGroupMapper.updateById(wxUserBusinessCategoryGroup);
            }

            if (businessCategoryRuleGroupInsDto.getWxUserIds() != null) {
                for (Long wxUserId : businessCategoryRuleGroupInsDto.getWxUserIds()) {
                    //查询用户是否参与
                    List<WxUserBusinessCategoryGroup> result = businessCategoryRuleMapper.selectBusinessCategoryRule4startId(wxUserId, businessCategoryRule.getId());
                    if (result.size() > 0) {
                        FeignWxUserDto feignWxUserDto = wxUserApiFeign.selectFeignWxUserDtoByWxUserId(wxUserId);
                        throw new ServiceException("用户" + feignWxUserDto.getNickname() + "已经参与此星级认证");
                    }
                }
            }

            //重新分配
            for (Long wxUserId : businessCategoryRuleGroupInsDto.getWxUserIds()) {
                WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = wxUserBusinessCategoryGroupMapper.selectOne(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                        .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryRuleGroupInsDto.getBusinessCategoryRuleId())
                        .eq(WxUserBusinessCategoryGroup::getType, 0)
                        .eq(WxUserBusinessCategoryGroup::getWxUserId, wxUserId));
                //如果不存在则添加上去
                if (wxUserBusinessCategoryGroup == null) {
                    WxUserBusinessCategoryGroup save = new WxUserBusinessCategoryGroup();
                    save.setCommonId(businessCategoryRuleGroup.getId());
                    save.setEnterpriseId(enterpriseId);
                    save.setType(0);
                    save.setWxUserId(wxUserId);
                    wxUserBusinessCategoryGroupMapper.insert(save);
                } else {
                    //如果存在则直接改为可考
                    wxUserBusinessCategoryGroup.setExamStatus(0);
                    wxUserBusinessCategoryGroupMapper.updateById(wxUserBusinessCategoryGroup);
                }
            }
        }
        return new ReturnVO("添加或修改星级认证班组成功", businessCategoryRuleGroupInsDto.getId());
    }

    @Autowired
    private EvaluationProducer evaluationProducer;

    @Override
    public ReturnVO<JgPageVo<WxUserBusinessCategoryGroup>> selectWxUserBusinessCategoryGroupByBusinessCategoryRuleGroupId(Long enterpriseId, WxUserBusinessCategoryGroupDto wxUserBusinessCategoryGroupDto) {
        BusinessCategoryRuleGroup businessCategoryRuleGroup = businessCategoryRuleGroupMapper.selectById(wxUserBusinessCategoryGroupDto.getWxUserBusinessCategoryGroupId());
        Optional.ofNullable(businessCategoryRuleGroup).orElseThrow(() -> new ServiceException("该id对应的星级认证班组不存在"));
        PageHelper.startPage(wxUserBusinessCategoryGroupDto.getCurPage(), wxUserBusinessCategoryGroupDto.getMaxPage());
        List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroups = wxUserBusinessCategoryGroupMapper.selectList(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                .eq(WxUserBusinessCategoryGroup::getCommonId, wxUserBusinessCategoryGroupDto.getWxUserBusinessCategoryGroupId())
                .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                .eq(WxUserBusinessCategoryGroup::getType, 0)
                .eq(WxUserBusinessCategoryGroup::getEnterpriseId, enterpriseId));
        for (WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup : wxUserBusinessCategoryGroups) {
            //查询用户信息
            ReturnVO<String> stringReturnVO = wxUserApiFeign.selectWxUserByWxUserId(wxUserBusinessCategoryGroup.getWxUserId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            wxUserBusinessCategoryGroup.setNickname(jsonObject.getString("nickname"));
            wxUserBusinessCategoryGroup.setIcon(jsonObject.getString("icon"));
            wxUserBusinessCategoryGroup.setPhone(jsonObject.getString("phone"));
            wxUserBusinessCategoryGroup.setOrganizationName(jsonObject.getString("organizationName"));
            wxUserBusinessCategoryGroup.setIdentityName(jsonObject.getString("identityName"));
        }
        return new ReturnVO("绑定人员查询成功", new JgPageVo<>(new PageInfo(wxUserBusinessCategoryGroups)));
    }


    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryRuleGroup>>> listBusinessCategoryRuleGroup(Long enterpriseId, BusinessCategoryRuleGroupDto businessCategoryRuleGroupDto) {
        PageHelper.startPage(businessCategoryRuleGroupDto.getCurPage(), businessCategoryRuleGroupDto.getMaxPage());
        QueryWrapper<BusinessCategoryRuleGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enterprise_id", enterpriseId);
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.isNotBlank(businessCategoryRuleGroupDto.getRuleName())) {
            queryWrapper.like("rule_name", businessCategoryRuleGroupDto.getRuleName() + "%");
        }
        List<BusinessCategoryRuleGroup> businessCategoryRuleGroups = businessCategoryRuleGroupMapper.selectList(queryWrapper);
        for (BusinessCategoryRuleGroup businessCategoryRuleGroup : businessCategoryRuleGroups) {
            ReturnVO<String> stringReturnVO = enterpriseOrganizationApiFeign.selectOrganizationById(businessCategoryRuleGroup.getEnterpriseOrganizationId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            businessCategoryRuleGroup.setOrganizationName(jsonObject.getString("organizationName"));
        }
        return new ReturnVO("添加或修改星级认证班组成功", new JgPageVo<>(new PageInfo(businessCategoryRuleGroups)));
    }

    @Autowired
    private IEnterpriseApiFeign enterpriseApiFeign;

    @Override
    public ReturnVO saveWxUserBusinessCategoryGroup4factory(Long enterpriseId, WxUserBusinessCategoryGroup4factoryDto wxUserBusinessCategoryGroup4factoryDto) {
        ReturnVO<String> stringReturnVO = enterpriseApiFeign.selectEnterpriseById(enterpriseId);
        JSONObject returnJsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
        BusinessCategoryRule factory = businessCategoryRuleMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRule>()
                .eq(BusinessCategoryRule::getBusinessCategoryId, returnJsonObject.getLong("businessCategoryId"))
                .eq(BusinessCategoryRule::getType, 0));
        Optional.ofNullable(factory).orElseThrow(() -> new ServiceException("该企业的行业没有工厂体检"));
        if (wxUserBusinessCategoryGroup4factoryDto.getWxUserIds() != null) {
            //先全部禁考
            List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroups = wxUserBusinessCategoryGroupMapper.selectList(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                    .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                    .eq(WxUserBusinessCategoryGroup::getType, 1)
                    .eq(WxUserBusinessCategoryGroup::getCommonId, factory.getId()));
            for (WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup : wxUserBusinessCategoryGroups) {
                //禁考
                wxUserBusinessCategoryGroup.setExamStatus(1);
                wxUserBusinessCategoryGroupMapper.updateById(wxUserBusinessCategoryGroup);
            }
            //重新分配
            for (Long wxUserId : wxUserBusinessCategoryGroup4factoryDto.getWxUserIds()) {
                WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = wxUserBusinessCategoryGroupMapper.selectOne(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                        .eq(WxUserBusinessCategoryGroup::getCommonId, factory.getId())
                        .eq(WxUserBusinessCategoryGroup::getType, 0)
                        .eq(WxUserBusinessCategoryGroup::getWxUserId, wxUserId));
                //如果不存在则添加上去
                if (wxUserBusinessCategoryGroup == null) {
                    WxUserBusinessCategoryGroup save = new WxUserBusinessCategoryGroup();
                    save.setCommonId(factory.getId());
                    save.setEnterpriseId(enterpriseId);
                    save.setType(1);
                    save.setWxUserId(wxUserId);
                    wxUserBusinessCategoryGroupMapper.insert(save);
                } else {
                    //如果存在则直接改为可考
                    wxUserBusinessCategoryGroup.setExamStatus(0);
                    wxUserBusinessCategoryGroupMapper.updateById(wxUserBusinessCategoryGroup);
                }
            }
        }
        return new ReturnVO("人员分配成功", factory.getId());
    }

    @Override
    public ReturnVO selectFactoryBind(Long enterpriseId, SelectFactoryBindDto selectFactoryBindDto) {
        ReturnVO<String> stringReturnVO = enterpriseApiFeign.selectEnterpriseById(enterpriseId);
        JSONObject returnJsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
        BusinessCategoryRule factory = businessCategoryRuleMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRule>()
                .eq(BusinessCategoryRule::getBusinessCategoryId, returnJsonObject.getLong("businessCategoryId"))
                .eq(BusinessCategoryRule::getType, 0));
        Optional.ofNullable(factory).orElseThrow(() -> new ServiceException("该企业的行业没有工厂体检"));
        PageHelper.startPage(selectFactoryBindDto.getCurPage(), selectFactoryBindDto.getMaxPage());
        List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroups = wxUserBusinessCategoryGroupMapper.selectList(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                .eq(WxUserBusinessCategoryGroup::getCommonId, factory.getId())
                .eq(WxUserBusinessCategoryGroup::getExamStatus, 0)
                .eq(WxUserBusinessCategoryGroup::getType, 1)
                .eq(WxUserBusinessCategoryGroup::getEnterpriseId, enterpriseId));
        for (WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup : wxUserBusinessCategoryGroups) {
            //查询用户信息
            ReturnVO<String> returnVO = wxUserApiFeign.selectWxUserByWxUserId(wxUserBusinessCategoryGroup.getWxUserId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(returnVO);
            wxUserBusinessCategoryGroup.setNickname(jsonObject.getString("nickname"));
            wxUserBusinessCategoryGroup.setIcon(jsonObject.getString("icon"));
            wxUserBusinessCategoryGroup.setPhone(jsonObject.getString("phone"));
            wxUserBusinessCategoryGroup.setOrganizationName(jsonObject.getString("organizationName"));
            wxUserBusinessCategoryGroup.setIdentityName(jsonObject.getString("identityName"));
        }
        return new ReturnVO("绑定人员查询成功", new JgPageVo<>(new PageInfo(wxUserBusinessCategoryGroups)));
    }

    @Override
    public Integer selectWxUserStart(Long wxUserId) {
        BusinessCategoryRuleHistory businessCategoryRuleHistory = businessCategoryRuleHistoryMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getWxUserId, wxUserId)
                .orderByDesc(BusinessCategoryRuleHistory::getStartLevel)
                .select(BusinessCategoryRuleHistory::getStartLevel).last("limit 0,1"));
        if (businessCategoryRuleHistory != null && businessCategoryRuleHistory.getStartLevel() != null) {
            return businessCategoryRuleHistory.getStartLevel();
        }
        return 0;
    }


    @Override
    public ReturnVO<CredentialListVo> selectCredentialListVo(JSONObject jsonObject) {
        CredentialListVo credentialListVo = new CredentialListVo();
        List<BusinessCategoryRuleGroup> businessCategoryRuleGroupList = businessCategoryRuleGroupMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleGroup>()
                .eq(BusinessCategoryRuleGroup::getEnterpriseId, jsonObject.getLong("enterpriseId"))
                .eq(BusinessCategoryRuleGroup::getRuleName, "五星班组")
                .orderByDesc(BusinessCategoryRuleGroup::getCreateTime));
        List<BusinessCategoryRuleHistory> businessCategoryRuleHistoryList = businessCategoryRuleHistoryMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getType, 1)
                .eq(BusinessCategoryRuleHistory::getWxUserId, jsonObject.getLong("id"))
                .orderByDesc(BusinessCategoryRuleHistory::getCreateTime));
        List<BusinessCategoryRuleHistory> businessCategoryRuleHistoryEnterpriseList = businessCategoryRuleHistoryMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                .eq(BusinessCategoryRuleHistory::getEnterpriseId, jsonObject.getLong("enterpriseId"))
                .eq(BusinessCategoryRuleHistory::getType, 0)
                .orderByDesc(BusinessCategoryRuleHistory::getCreateTime));
        //企业证书列表
        List<CredentialVo> credentialEnterpriseVos = Lists.newArrayList();
        for (BusinessCategoryRuleHistory businessCategoryRuleHistory : businessCategoryRuleHistoryEnterpriseList) {
            CredentialVo credentialVo = new CredentialVo();
            credentialVo.setStarName(businessCategoryRuleHistory.getStartLevel() + "星企业");
            credentialVo.setCreateTime("获得日期:" + businessCategoryRuleHistory.getCreateTime().toLocalDate().toString());
            credentialVo.setCredentialUrl(businessCategoryRuleHistory.getCredentialUrl());
            credentialEnterpriseVos.add(credentialVo);
        }
        //班组证书列表
        List<CredentialVo> credentialGroupVos = Lists.newArrayList();
        for (BusinessCategoryRuleGroup businessCategoryRuleGroup : businessCategoryRuleGroupList) {
            CredentialVo credentialVo = new CredentialVo();
            credentialVo.setStarName(businessCategoryRuleGroup.getDesignation());
            credentialVo.setCreateTime("获得日期:" + businessCategoryRuleGroup.getCreateTime().toLocalDate().toString());
            credentialVo.setCredentialUrl(businessCategoryRuleGroup.getCredentialUrl());
            credentialGroupVos.add(credentialVo);
        }
        //个人证书列表
        List<CredentialVo> credentialPersonVos = Lists.newArrayList();
        for (BusinessCategoryRuleHistory businessCategoryRuleHistory : businessCategoryRuleHistoryList) {
            CredentialVo credentialVo = new CredentialVo();
            credentialVo.setStarName(businessCategoryRuleHistory.getStartLevel() + "星");
            credentialVo.setCreateTime("获得日期:" + businessCategoryRuleHistory.getCreateTime().toLocalDate().toString());
            credentialVo.setCredentialUrl(businessCategoryRuleHistory.getCredentialUrl());
            credentialPersonVos.add(credentialVo);
        }
        credentialListVo.setCredentialEnterpriseVos(credentialEnterpriseVos);
        FeignEnterpriseDto feignEnterpriseDto = enterpriseApiFeign.selectEnterpriseDtoById(jsonObject.getLong("enterpriseId"));
        credentialListVo.setEnterpriseStar(feignEnterpriseDto.getEnterpriseLevel());
        credentialListVo.setCredentialGroupVos(credentialGroupVos);
        //查看是否有五星
        credentialListVo.setGroupStar(businessCategoryRuleGroupList.size() == 0 ? 0 : 5);
        credentialListVo.setCredentialPersonVos(credentialPersonVos);
        credentialListVo.setPersonStar(selectWxUserStart(jsonObject.getLong("id")));
        return new ReturnVO("查询星级认证证书", credentialListVo);
    }

    @Autowired
    private BusinessCategoryRuleGroupStatisticsDataMapper businessCategoryRuleGroupStatisticsDataMapper;

    @SneakyThrows
    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryRuleGroupStatisticsData>>> selectBusinessCategoryRuleGroupStatisticsDataByGroup(HttpServletResponse response, Long enterpriseId, BusinessCategoryRuleGroupStatisticsDataByGroupDto businessCategoryRuleGroupStatisticsDataByGroupDto) {
        PageHelper.startPage(businessCategoryRuleGroupStatisticsDataByGroupDto.getCurPage(), businessCategoryRuleGroupStatisticsDataByGroupDto.getMaxPage());
        BusinessCategoryRuleGroupStatisticsDataDto businessCategoryRuleGroupStatisticsDataDto = new BusinessCategoryRuleGroupStatisticsDataDto();
        businessCategoryRuleGroupStatisticsDataDto.setEndTime(LocalDate.now().toString());
        //近7天
        if (businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() != null && businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() == 0) {
            businessCategoryRuleGroupStatisticsDataDto.setStartTime(LocalDate.now().minusDays(7).toString());
        }
        //近30天
        if (businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() != null && businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() == 1) {
            businessCategoryRuleGroupStatisticsDataDto.setStartTime(LocalDate.now().minusDays(30).toString());
        }
        //近365天
        if (businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() != null && businessCategoryRuleGroupStatisticsDataByGroupDto.getLastDay() == 2) {
            businessCategoryRuleGroupStatisticsDataDto.setStartTime(LocalDate.now().minusDays(365).toString());
        }
        //查询部门信息
        List<BusinessCategoryRuleGroupStatisticsData> businessCategoryRuleGroupStatisticsDataList = businessCategoryRuleGroupStatisticsDataMapper.selectSumByStudyTime(enterpriseId, businessCategoryRuleGroupStatisticsDataDto);
        for (BusinessCategoryRuleGroupStatisticsData businessCategoryRuleGroupStatisticsData : businessCategoryRuleGroupStatisticsDataList) {
            ReturnVO<String> stringReturnVO = wxUserApiFeign.selectOrganizationById(businessCategoryRuleGroupStatisticsData.getEnterpriseOrganizationId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            businessCategoryRuleGroupStatisticsData.setOrganizationName(jsonObject.getString("organizationName"));
        }
        if (businessCategoryRuleGroupStatisticsDataByGroupDto.getIsExport() != null && businessCategoryRuleGroupStatisticsDataByGroupDto.getIsExport() == 1) {
            ExcelUtils.exportExcel(businessCategoryRuleGroupStatisticsDataList, "班组排名", "班组排名", BusinessCategoryRuleGroupStatisticsData.class, "班组排名", response);
            return new ReturnVO("班组排名导出成功", null);
        }
        return new ReturnVO("班组排名查询成功", new JgPageVo<>(new PageInfo(businessCategoryRuleGroupStatisticsDataList)));
    }
}
